<template>
  <div id="app">
    <topbar class="topbar"></topbar>
    <!-- <h1 class="title">个人中心</h1> -->
    <div class="box">
      <!-- <el-avatar
        size="medium"
        :src="'http://www.liujn.top/bbs/api' + this.$cookies.get('UserAvatar')"
        class="avatar"
      ></el-avatar> -->
      <div class="main">
        <el-upload
          class="avatar-uploader"
          action="#"
          :http-request="httpRequest"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
        >
          <el-image
            v-if="this.imageUrl"
            :src="this.imageUrl"
            class="avatar"
            fit="cover"
          ></el-image>
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>

        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          class="demo-ruleForm"
        >
          <el-form-item prop="user">
            <el-input
              v-model="ruleForm.user"
              disabled
              :placeholder="this.user.username"
            ></el-input>
          </el-form-item>

          <el-form-item prop="mail">
            <el-input placeholder="邮箱" v-model="ruleForm.mail"  disabled></el-input>
          </el-form-item>

          <el-form-item prop="information">
            <el-input type="textarea" v-model="ruleForm.information" placeholder="这个人是个懒棒，什么都没写"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="submitForm('ruleForm')"
              class="first_btn"
              :loading="loading"
              >确认更新</el-button
            >
            <el-button @click="loginOut()" class="second_btn" type="danger">退出登录</el-button>
            <el-button @click="back()" class="second_btn">返回</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <footbar class="footbar"></footbar>
  </div>
</template>

<script>
import topbar from "../public/topbar.vue";
import footbar from "../public/footbar.vue";
export default {
  name: "",
  data() {
    return {
      ruleForm: {
        user: "",
        mail: "",
        information: ""
      },
      rules: {
        user: [],
        mail: [
          { message: "请输入邮箱", trigger: "blur" },
          { type: "email", message: "邮箱格式错误", trigger: "blur" },
          { max: 255, message: "你邮箱这么长?", trigger: "blur" }
        ],
        information: [
          { message: "请输入个人信息", trigger: "blur" },
          { max: 255, message: "个人信息长度在 255 个字符以内", trigger: "blur" }
        ],
      },
      user: [],
      imageUrl: "",
      formData: {},
      file: {},
      loading: false,
      avatarChange: false
    };
  },
  mounted() {
    this.getUser(), this.setFormData();
  },
  methods: {
    getUser() {
      if (this.$cookies.isKey("CookieId")) {
        this.axios
          .get("http://www.liujn.top/bbs/api/user/seek/personal", {
            params: {
              username: this.$cookies.get("UserName"),
            },
          })
          .then((res) => {
            // console.log(res.data);
            this.user = res.data;
            this.formData.append("username", this.user.username);
            this.imageUrl = "http://www.liujn.top/bbs/api" + res.data.avatar;
            this.ruleForm.mail = this.user.mailbox;
            this.ruleForm.information = this.user.information;
          });
      } else {
        this.$router.push("/article");
        this.$message.error("要访问个人中心，请先登录");
      }
    },
    setFormData() {
      this.formData = new FormData();
    },
    loginOut() {
      this.$cookies.remove("CookieId");
      this.$cookies.remove("UserName");
      this.$cookies.remove("UserAvatar");
      this.$router.push("/article");
    },
    beforeAvatarUpload(file) {
      let fileName = new Date().getTime().toString()
      if(file.type == "image/jpeg") {
        fileName = fileName + ".jpg"
      } else if (file.type == "image/png") {
        fileName = fileName + ".png"
      } else {
        fileName = fileName + ".???"
      }
      const copyFile = new File([file], fileName, {type: file.type})
      const isJPG = (copyFile.type === "image/jpeg") || (copyFile.type === "image/png");
      const isLt2M = copyFile.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 或 PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      this.file = copyFile
      return isJPG && isLt2M;
    },
    httpRequest (data) {
      let rd = new FileReader()
      let file = data.file
      rd.readAsDataURL(file)
      rd.onloadend = (e) => {
        this.imageUrl = e.target.result
      }
      this.avatarChange = true
    },
    //表单
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true
          if (this.avatarChange) {
            this.formData.append("avatar", this.file);
          }
          this.formData.append("information", this.ruleForm.information);
          this.axios.post("http://www.liujn.top/bbs/api/user/update", this.formData).then((res) => {
            if (res.data == '-0' | '-5') {
              this.axios.get("http://www.liujn.top/bbs/api/user/seek/personal", { params: {
                username: this.$cookies.get("UserName")
              }}).then((res) => {
                if (this.avatarChange) {
                  this.$cookies.remove("UserAvatar")
                  this.$cookies.set("UserAvatar", res.data.avatar)
                }
                this.$message({
                  type: "success",
                  message: "更新成功！",
                  offset: 50
                })
                this.$router.push('/article')
              })
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    back() {
      this.$router.go(-1)
    }
  },
  components: {
    topbar,
    footbar,
  },
};
</script>

<style scoped>
#app {
  background-image: url("../../assets/login_bg.jpg");
  background-size: 1920px 100%;
  background-repeat: no-repeat;
}

.topbar {
  width: 100%;
  position: fixed;
  top: 0;
  z-index: 1;
}

.footbar {
  width: 100%;
  position: absolute;
  bottom: 0px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  display: block;
  margin-bottom: 40px;
}

.box {
  width: 80%;
  height: 100vh;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  justify-content: center;
  /* background-color: #fff; */
}

.main {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.title {
  color: white;
}

.demo-ruleForm {
  margin: 0px auto;
  /* transform: translateX(-44px); */
  width: 100%;
  max-width: 450px;
  /* background-color: #000; */
}

div /deep/.el-form-item__label {
  color: white;
}
</style>
